#-*- coding: utf-8 -*-

import serial
import time
import numpy as np
import pandas as pd
import json
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

ser_1 = serial.Serial('COM10', 230400, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
# ser = serial.Serial('COM11', 9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)

data_to_send = [0x03,0x03,0x02,0xE3,0x00,0x01,0x75,0xA6]
# time.sleep(0.8)
# count = ser.in_waiting
# data = ser.read(count)
# ser.close()
# print(count)
# print(data)
# for i in data:
#     print(i,end="~")

"""
一、身份，负荷是什么
二、状态，工作状态（充电，涓流、恒压；热水壶，加热保温关闭）
三、事件，从一种状态到另一种状态的暂态过程
什么时间有什么负荷，工作状态如何；什么时间发生状态变化

训练，算法流程，算法参数保存，算法输入输出

在线运行，决策逻辑
"""

def get_data_to_receive():

    address = ser.read(1)
    function_code = ser.read(1)
    data_length = ser.read(1)
    packets = [address, function_code, data_length]
    length = int.from_bytes(data_length, byteorder='little', signed=False)
    #带校验位检测
    # data_ten = 0
    # for i in range(length):
    #     data_byte = ser.read(1)
    #     packets.append(data_byte)
    #     data_ten = data_ten * 256 + int.from_bytes(data_byte, 'big')
    # data = data_ten / 10
    # a = b''
    # c = a.join(packets)
    # crc = calculate_crc16(c)
    # crc_high = crc // 256
    # crc_low = crc % 256
    # crc_low_test = int.from_bytes(ser.read(1), 'big')
    # crc_high_test = int.from_bytes(ser.read(1), 'big')
    # if not ((crc_low_test == crc_low) and (crc_high_test == crc_high)):
    #     print("error")
    #不带校验位检测
    data_bytes = ser.read(length)
    data_ten = int.from_bytes(data_bytes, 'big')
    data = data_ten / 10
    ser.read(1)
    ser.read(1)
    return data

cnt = 40
data = b''
data_v = 0
count = 0
current_list = []
voltage_list = []
current = 0
time_start = time.time()
while cnt > 0:
    time.sleep(0.5)
    cnt = cnt - 1
    count_temp = ser_1.in_waiting
    data_temp = ser_1.read(count_temp)
    data = data + data_temp
    count = count + count_temp
    ser.write(bytes(data_to_send))
    data_v = get_data_to_receive()
    voltage_list.append(data_v)

time_end = time.time()
time_elapsed = time_end - time_start
print(count)
# print(data)
print(time_elapsed)

time_start = time.time()
odd = True

# for i in data:
#     if odd:
#         num = i
#         odd = False
#     else:
#         num = num*256 + i
#         num_list.append(num)
#         odd = True
for i in range(0, count, 2):
    current = data[i]*256 + data[i+1]
    if(current >= 32768):
        current = current - 65536
    current_list.append(current)

# t = range(len(current_list))
ave = np.mean(current_list)
current_list2 = [x-ave for x in current_list]
time_end = time.time()
time_elapsed = time_end - time_start
# print(current_list2)
print(len(current_list2))
print(time_elapsed)
print(ave)

t = range(len(current_list2))
t_v = range(len(voltage_list))
fig=plt.figure(figsize=(5,4))
plt.title('测量数据暂态变化曲线')  # 设置标题
# plt.plot(t,current_list,alpha = 0.5,marker='o',markersize=5)
plt.plot(t,current_list2)
plt.show()

dic1 = dict(zip(t,current_list2))

# write_dict('test.txt',dic1)
# dic2 = read_dict('data_of_kettle.txt')
series1 = pd.Series(dic1)
series1.to_csv(f'test{int(1000*time.time())}.csv')

series_current = pd.Series(current_list2,index=t)
series_voltage = pd.Series(voltage_list,index=t_v)

d = {'current':series_current,'voltage':series_voltage}
df = pd.DataFrame(d)
df.to_csv(f'current_data{int(1000*time.time())}.csv')